//
//  NoteDAO.swift
//  MyNoteDemo4
//
//  Created by BZF on 2020/8/24.
//  Copyright © 2020 bzf. All rights reserved.
//

import Foundation
import CoreData

public class NoteDao: CoreDataDAO{
     
    private var dateFormatter = DateFormatter()
    
    public static let instance: NoteDao = {
        let instance = NoteDao()
        
        instance.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        return instance
    }()
    
    public func insert(_ mode: Note) -> Int {
        let context = persistentContainer.viewContext
        
        let note = NSEntityDescription.insertNewObject(forEntityName: "DBNote", into: context) as! DBNote
        note.date = mode.date as Date
        note.content = mode.content
        self.saveContext()
        
        return 0
    }
    
    public func remove(_ mode: Note) -> Int {
        
        return 0
    }
    
    public func modify(_ model: Note) -> Int {
        
        return 0
    }
    
    public func findAll() -> NSMutableArray {
        let context = persistentContainer.viewContext
        //返回Core Data实体对象
        let entity = NSEntityDescription.entity(forEntityName: "DBNote", in: context)
        
        //创建一个请求数据对象
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
        fetchRequest.entity = entity
        
        //设置排序方式
        let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
        let sortDescriptors = [sortDescriptor]
        fetchRequest.sortDescriptors = sortDescriptors
        
        let resultListData = NSMutableArray()
        
        do {
            let listData = try context.fetch(fetchRequest)
            
            if listData.count > 0{
                for item in listData{
                    let dbNote = item as! DBNote
                    let note = Note(date: dbNote.date! as NSDate, content: dbNote.content!)
                    resultListData.add(note)
                }
            }
        } catch  {
            print("查询数据失败")
        }
        return resultListData
    }
    
    public func findById(_ mode: Note) -> Note?{
         return nil
    }
}
